package com.imm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.imm.common.Result;
import com.imm.dto.DishDTO;
import com.imm.dto.SetmealDTO;
import com.imm.mapper.SetmealMapper;
import com.imm.pojo.*;
import com.imm.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements ISetmealService {

    @Resource
    private ICategoryService categoryService;

    @Resource
    private ISetmealDishService setmealDishService;

    @Resource
    private IDishService dishService;

    @Resource
    private IDishFlavorService dishFlavorService;


    @Resource
    private SetmealMapper setmealMapper;


    /**
     * 分页查询
     * @param page 页数
     * @param pageSize 页大小
     * @param name 名称
     * @return 响应
     */
    @Override
    public Result<Page> pageSetmeal(int page, int pageSize, String name) {
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);
        Page<SetmealDTO> setmealDTOPage = new Page<>();
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(name), Setmeal::getName, name);
        wrapper.orderByDesc(Setmeal::getPrice);
        page(pageInfo, wrapper);
        BeanUtils.copyProperties(pageInfo, setmealDTOPage, "records");
        List<Setmeal> records = pageInfo.getRecords();
        List<SetmealDTO> setmealDTOS = new ArrayList<>();
        setmealDTOS = records.stream().map((item) -> {
            SetmealDTO setmealDTO = new SetmealDTO();
            Category category = categoryService.getById(item.getCategoryId());
            BeanUtils.copyProperties(item, setmealDTO);
            setmealDTO.setCategoryName(category.getName());
            log.info("{}", setmealDTO);
            return setmealDTO;
        }).collect(Collectors.toList());
        setmealDTOPage.setRecords(setmealDTOS);
        return Result.success(setmealDTOPage);
    }

    /**
     * 新增套餐
     * @param setmealDTO 套餐数据传输对象
     * @return 响应
     */
    @Transactional
    @Override
    public Result<String> insert(SetmealDTO setmealDTO) {
        setmealMapper.insert(setmealDTO);
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        setmealDishes = setmealDishes.stream().map((item) -> {
            item.setSetmealId(setmealDTO.getId().toString());
            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishes);
        return Result.success("新增成功");
    }

    /**
     * 起售或停售
     * @param status 状态值 1 起售 0 停售
     * @param ids id数组
     * @return 响应
     */
    @Override
    public Result<String> changeStatus(Integer status, Long[] ids) {
        LambdaUpdateWrapper<Setmeal> wrapper = new LambdaUpdateWrapper<>();
        List<Long> list = List.of(ids);
        wrapper.set(Setmeal::getStatus, status).in(Setmeal::getId, list);
        update(wrapper);
        return Result.success("修改成功");
    }

    /**
     * 批量删除
     * @param ids id数组
     * @return 相应
     */
    @Transactional
    @Override
    public Result<String> delete(Long[] ids) {
        List<Long> list = List.of(ids);
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.in(Setmeal::getId, list);
        List<Setmeal> setmeals = list(setmealLambdaQueryWrapper);
        List<String> setmealIdList = new ArrayList<>();
        setmeals.forEach( item -> {
            // 读取id
            setmealIdList.add(item.getId().toString());
        });
        // 先在关系表中删除
        LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishLambdaQueryWrapper.in(SetmealDish::getSetmealId, setmealIdList);
        setmealDishService.remove(setmealDishLambdaQueryWrapper);
        // 再删除自己
        remove(setmealLambdaQueryWrapper);
        return Result.success("操作成功");
    }

    @Override
    public Result<List<Setmeal>> listSetmeal(Setmeal setmeal) {
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId())
                .eq(setmeal.getId() != null, Setmeal::getId, setmeal.getId())
                .eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus());
        List<Setmeal> setmeals = list(wrapper);
        return Result.success(setmeals);
    }

    @Transactional
    @Override
    public Result<List<DishDTO>> dishList(Long id) {
        // 先查关系表
        LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishLambdaQueryWrapper.eq(SetmealDish::getSetmealId, id.toString());
        List<SetmealDish> setmealDishes = setmealDishService.list(setmealDishLambdaQueryWrapper);
        // dishId
        List<DishDTO> dishDTOList = setmealDishes.stream().map(item -> {
            DishDTO dishDTO = new DishDTO();
            Dish dish = dishService.getById(Long.parseLong(item.getDishId()));
            BeanUtils.copyProperties(dish, dishDTO);
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, dish.getId());
            List<DishFlavor> dishFlavors = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
            dishDTO.getFlavors().addAll(dishFlavors);
            Category category = categoryService.getById(dish.getCategoryId());
            dishDTO.setCategoryName(category.getName());
            dishDTO.setCopies(item.getCopies());
            return dishDTO;
        }).collect(Collectors.toList());
        return Result.success(dishDTOList);
    }

}